home *** CD-ROM | disk | FTP | other *** search
/ MacWorld 1999 May / Macworld (1999-05).dmg / Shareware World / Info / Apple Wizards - Mar 1999 / Apple Wizards - March 1999 / Apple Wizards - March 1999.rsrc / TEXT_144.txt < prev    next >
Text File  |  1999-03-03  |  11KB  |  178 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15. Welcome Back!
  16.  
  17. Welcome to the second in what I hope will be a long series of columns crafted to help you learn to program on the Macintosh, or just learn to program better in general. Since this publication and its back issues will be forever available on the Apple Wizards website, I've decided to start from the beginning, and work up from there. What will you need to begin this journey? A basic introductory understanding of the C language, perhaps enough to create a 'hello world' program and run it. I'm going to assume that your only exposure to Mac OS programming was with a simple "console app" that you copied out of a book. In other words, you can pack light for this journey ‚Äî there's plenty of food along the way.
  18.  
  19. You should also know what you can expect out of this. By the time the fourth installment of my column in AppleWizards hits the virtual stands, you can expect to know how to create a true Mac OS program, and you'll understand many of the basics. This doesn't mean you'll be ready to snap your fingers and create the next Tomb Raider. Mac OS programming in C is quite a lengthy and complex procedure. But it does create some of the smallest programs (in terms of size of finished applications), and is the best way to get a handle on just what your Mac is capable of. Also, by the fourth installment, you should be ready to start learning on your own quite easily. But more on that later.
  20.  
  21. Patience is a great virtue when it comes to programming. You'd be amazed at the kinds of trouble you'll encounter, and how easy it is to create really nasty bugs in your code. I suggest (and I do this myself) that you keep a diary of your problems. Not your progress, not what you've learned, but rather what you haven't learned. The reason for this is that you'll very quickly realize just what your weaknesses are. Also, once you get bitten again by the same exact out-of-place comma, semicolon, or bracket, you'll be ready to pull your few remaining hairs out. So keep a diary. Keep track of every problem you encounter, what the symptoms were, and most importantly, how you fixed it.
  22.  
  23. This column will focus on C and the underlying concepts which propel the Macintosh Operating System. However, C isn't the only way to go about programming. The right tool for the job is the key here. There are several excellent Rapid Application Design (RAD) tools on the market, such as RealBasic and SuperCard, which can do the hard and boring work for you. But to extend most of those languages, you'll need C. You'll never encounter boundaries you can't cross using C. Once you've written an entire application in C, you'll know everything you'll need to know about working with the Mac OS Toolbox, and if you don't, you'll know where to find it.
  24.  
  25. Lastly, there are many fine books on programming. I'll be doing short reviews of some of them in the coming months, so stay tuned. I've read around a dozen or so Mac Programming books, and although I can't say just which one was my favorite, or the easiest to understand, none of them really sucked. So if you're considering buying a Mac programming book, go right ahead.
  26.  
  27. Note
  28. You'll hear a phrase thrown around a lot among Mac OS programmers, the "Toolbox." No, you don't need to go buy it. The easiest way to explain it is by example. Rather than let you try to figure out how the Mac speakers work, how to find the current "beep" sound, load it into RAM, create a sound channel, play it through the speakers, close the sound channel, dispose of the RAM, etc., Apple figured people would want to be able to do this regularly, so they created a function, "SysBeep," which when called will simply play the current beep sound. There are hundreds of such utilities, and they are collectively known as the Mac OS Toolbox. So now you know.
  29.  
  30.  
  31.  
  32.  
  33. The Event Loop
  34.  
  35. The first concept I'm going to introduce you to will be the one of the most difficult and odd concepts you'll get the experience of wrapping your mind around in the entire course of programming on the Mac. Ever wonder how your Mac knows what to do when you click a menu, for instance? To your Mac, the world is nothing more than a series of events and responses. And that's the topic for today, the most important underlying concept in Macintosh programming. It's called the "Event Loop," and it is deceptively simple.
  36.  
  37. The event loop is like a train, and each program can be thought of as a station. Each app can tell the train to either drop off its cargo, continue to the next station, and more. In addition, each application can send events via the loop to other applications.
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54. If you're experienced with console programming, a common paradigm in the academic world, then the concept of an event loop is often somewhat unnerving. Don't be afraid, the Mac environment is just the same as a normal console program, except that the command line is constantly being handed back and forth between various programs. Okay, it's a little eerie. Every program you have open is waiting, right now, for you to do something. And if you aren't doing anything, then all of those programs are doing something on their own ‚Äî they're telling each other to wait until you do something else. We want your new program to fit in, so we'll teach it how to wait with the best of them. At the current time, there are only about eleven events that can occur on your Mac.
  55.  
  56. The Event List
  57. ‚Ä¢ Activate Event
  58. ‚Ä¢ Update Event
  59. ‚Ä¢ Drive Event
  60. ‚Ä¢ OS Event
  61. ‚Ä¢ High-level Event
  62. ‚Ä¢ Null Event 
  63. ‚Ä¢ Key-Down Event
  64. ‚Ä¢ Key-Up Event
  65. ‚Ä¢ AutoKey Event
  66. ‚Ä¢ Mouse-Down Event
  67. ‚Ä¢ Mouse-Up Event
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85. The OS sends these events around, and it's going to be your program's job (and therefore yours) to figure out which ones to watch for, which ones to act on, and which ones to ignore. Luckily, the "event" contains information about itself in a special type of data structure called an Event Record. All Event Records have the same structure, they just have different contents. Here's the anatomy of the standard event record:
  86.  
  87. Event Record
  88. ‚Ä¢ What
  89. ‚Ä¢ Message
  90. ‚Ä¢ Time
  91. ‚Ä¢ Mouse Location
  92. ‚Ä¢ Modifiers
  93.  
  94. The What section contains the type of event this is. It can be any of the eleven events mentioned above. For example, if your program is going to be AppleEvent aware (which is necessary for a program to be scriptable) then it's going to watch for High-level Events. If your program deals with files (most do), then you might want to watch for Drive Events. By checking the What section of the Event Record, you can decide how you want to respond.
  95.  
  96. The Message is where it gets interesting. In some cases, just knowing what happened is enough. For example, if you receive a mousedown event, you know that the mouse button was just pressed. But if you receive a key-down event, you probably want to know what key was pressed. The Message will sometimes be empty, but it will usually contain valuable data.
  97.  
  98. The Time is essentially a stamp that the Mac OS puts on each event so that you can know exactly when the event took place. It's actually the number of ticks since the Mac started up.
  99.  
  100. The Mouse Location (where) may be of great interest to you, especially if your app is watching for Mouse-Down events. You want to know where the mouse was when it was clicked, right?
  101.  
  102. And lastly the Modifier section will be flagged if there's one or more modifier keys being pressed. Modifier keys include the Command, Option, Control, Shift, and Caps Lock.
  103.  
  104.  
  105.  
  106.  
  107. Patience
  108.  
  109. Teaching your Mac to wait patiently is a simple thing. The Mac OS Toolbox function "WaitNextEvent" handles this for you. Simply call it, and your app will grab the next incoming event. This is the heart of the event loop. WaitNextEvent can take four parameters. 
  110.  
  111. The first is the Event Mask. By using special keywords, you can tell your Mac to only watch for certain events. But most of the time, you'll want them all to at least stop on the way through, so you'll probably pass "everyEvent" in this parameter.
  112.  
  113. The second is a pointer to an Event Record. When WaitNextEvent finishes, this event record will be filled out with the complete event info. 
  114.  
  115. The third is called a Sleep value, and it's the number of ticks that you're willing to go between checking for events. The larger the number, the more processing time you give other apps running at the same time. The lower the number gives your app more concurrent processing time. Hint: don't set it too low ‚Äî that is rude.
  116.  
  117. The fourth parameter is one you'll probably not use often, as it's reserved for apps that change the appearance of the cursor. So for this one, we'll pass 'nil' as our parameter.
  118.  
  119. Because your Mac app is event-driven, you'll want to place the call to WaitNextEvent() inside a loop. And since there are eleven different results you could see from that function, you'll probably want to catch that result with a switch. Following is an example which brings all of this together. Notice that this is a function. Some Mac programmers just keep their event loop in Main(), but I'm a 'modular' programmer, and I really like functions. It's up to you, ultimately. Here's the code‚Ķ
  120.  
  121. void  EventLoop( void ) // start the function
  122. {
  123.     EventRecord    theEvent;  // declare variables
  124.     
  125.    while ( gDone == false ) // gDone is a global, so repeat
  126.                             // the loop until we set
  127.                             // gDone to true
  128.    {
  129.       WaitNextEvent( everyEvent, &theEvent, 15L, nil );
  130.       //             \________/  \_______/  \_/  \_/
  131.       //                  |          |       |    |
  132.          // Capture all events          |       |    |
  133.       //                             |       |    |
  134.       //    Pass a pointer to a record       |    |
  135.       //                                     |    |
  136.       //       Check every 15 ticks (We use an    |
  137.       //        'L' to tell it to force the       |
  138.       //        15 to fill 4 bytes)               |
  139.       //                                          |
  140.       //         We don't change the cursor, so nil
  141.       //
  142.  
  143.          switch ( theEvent.what ) // switch using What
  144.          {
  145.                  case mouseDown:     // if it's a mousedown event...
  146.                     HandleMouseDown( theEvent ); // handle that.
  147.                     break;                       // and exit the switch
  148.  
  149.                  case updateEvt:       // if it's an update event...
  150.                     HandleMouseDown( theEvent ); // handle that.
  151.                     break;                       // and exit the switch
  152.  
  153.          } // end switch
  154.     } // end while
  155. } // end EventLoop function
  156.  
  157.  
  158.  
  159.  
  160.  
  161. Until Next Time...
  162.  
  163. Hopefully you've gained some insight into how your Mac actually works, and how the Event Loop is the center of the Universe. This understanding is crucial to being a good Mac OS programmer.
  164.  
  165. In coming months, we'll skim some topics for a while and then dig into the code rather deeply. 
  166.  
  167. Next month's column will be the bane of Systems everywhere, and the cause of more headaches and System Errors than nearly anything else‚Ķ Memory.
  168.  
  169.  
  170. ¬†          Chilton Webb
  171.            chilton@applewizards.net
  172.  
  173.  
  174.    
  175.  
  176.  
  177.                                              http://applewizards.net/
  178.